package com.adcc.loadsheet.billing.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.BillingBillEntity;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.exception.ParamValidException;
import com.adcc.loadsheet.billing.exception.PermissionVerifyException;
import com.adcc.loadsheet.billing.security.UserInfo;
import com.adcc.loadsheet.billing.service.BillingBillService;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.vo.BillingBillEntityVO;
import com.adcc.loadsheet.billing.vo.ResultStatus;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 计费帐单查询Controller层
 * Created by zhaoml on 2020/9/15.
 */
@Controller
@RequestMapping(value = "billingbill")
@Api(value = "/billingbill", description = "计费帐单查询相关操作controller")
public class BillingBillController extends BasisController{

    @Autowired
    BillingBillService billingBillService;

    @Autowired
    ContractUserService contractUserService;

    /**
     * 进入计费帐单查询页面
     * @param model
     * @return
     */
    @PreAuthorize("hasPermission('','BillingBillQuery')")
    @GetMapping(value = "tobillingbillquery")
    @ApiOperation(value = "/tobillingbillquery", notes = "跳转到计费帐单查询页面", httpMethod = "GET")
    public String toBillingBillQuery(Model model) {
        //将合同用户列表传到页面，用以选择
        // 合同用户关联的普通用户（并授权此功能菜单）可以查询当前合同的用户的舱单计费统计账单，管理员可以查询全部合同用户的计费统计账单
        Map<String, Object> map = Maps.newHashMap();
        UserInfo userInfo = userContext.getCurrentUser();
        if(!userInfo.isSuperAdmin()){
            map.put("PB_LOGIN_ID",userInfo.getUsername());
        }
        List<ContractUserEntity> contractUserList = contractUserService.select(map);
        model.addAttribute("contractUserList", contractUserList);
        return "billingBill/billingbill-query";
    }

    //查询计费帐单
    @PostMapping(value = "findBillingBill", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/findBillingBill", notes = "查询计费帐单", httpMethod = "POST")
    @ResponseBody
    public ResultVO findBillingBill(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            Map<String, Object> paramMap = inputContractUserParams(map);
            PageInfo<BillingBillEntityVO> billingBillPageInfo = billingBillService.selectBillingBillForPage(paramMap);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("voList", billingBillPageInfo);
        } catch (Exception ex) {
            Log.error(BillingBillController.class, "查询计费帐单出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query findBillingBill", ex.fillInStackTrace()));
            LogUtil.errorLog(BillingBillController.class,ex,"findBillingBill()");
        }
        return vo;
    }

    //下载文件
    @RequestMapping(value = "/exportfile")
    @ResponseBody
    public String exportFile(String billingFileName,String filePath,HttpServletResponse response){
        String result = billingBillService.exportFile(billingFileName,filePath,response);
        return result;
    }

    //上传执行账单文件
    @PostMapping(value = "editExecuteFile", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ResponseBody
    public void editExecuteFile(Integer id,
                                @RequestParam(value = "executeFile") MultipartFile multipartFile, HttpServletResponse response) throws Exception {
        String res;
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (null == multipartFile || multipartFile.isEmpty()) {
                out.print("请上传文件！");
                return;
            }
            BillingBillEntity billingBillEntity = billingBillService.selectByPrimaryKey(id);
            //更新执行账单
            billingBillService.edit(billingBillEntity, multipartFile);
            res = ResultStatus.SUCCESS.toString();
        } catch (Exception ex) {
            LogUtil.errorLog(BillingBillController.class, ex, "editExecuteFile()");
            res = "上传执行账单出错！";
        }
        out.print(res);
    }

    //编辑计费账单（执行金额和备注）
    @PostMapping(value = "editBillingBill", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/editBillingBill", notes = "编辑计费账单", httpMethod = "POST")
    @ResponseBody
    public ResultVO editBillingBill(@RequestBody Map<String, Object> map) throws Exception {
        ResultVO vo = new ResultVO();
        try {
            List<Object> billingBillEntityVOs = (List<Object>)map.get("billingBillEntityVOs");
            billingBillService.editExecute(billingBillEntityVOs);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("msg", "编辑成功！");
        } catch (Exception ex) {
            Log.error(BillingBillController.class, "编辑计费账单出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason("编辑计费账单出错");
            LogUtil.errorLog(BillingBillController.class, ex, "editBillingBill()");
        }
        return vo;
    }

    //导出excel
    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    @ApiOperation(value = "/excel", notes = "导出excel", httpMethod = "GET")
    public @ResponseBody
    void excel(String billingCycle,Integer contractUserId,HttpServletResponse response) {
        billingBillService.excel(billingCycle,contractUserId,response);
    }

    private Map<String, Object> inputContractUserParams(Map<String, Object> map) throws
            PermissionVerifyException, ParamValidException {
        Map<String, Object> paramMap = Maps.newHashMap();
        try {
            //查询月份
            String billingCycle = map.get("billingCycle") == null || "".equals(map.get("billingCycle")) ? "" : map.get("billingCycle").toString();
            //合同用户
            Integer contractUserId = map.get("contractUserId") == null || "".equals(map.get("contractUserId")) ? null : Integer.parseInt(map.get("contractUserId").toString());
            //第几页
            Integer pageNum = map.get("pageNum") == null || "".equals(map.get("pageNum")) ? 1 : Integer.parseInt(map.get("pageNum").toString());
            //每页页数
            Integer pageSize = map.get("pageSize") == null || "".equals(map.get("pageSize")) ? PAGE_SIZE_DEFAULT : Integer.parseInt(map.get("pageSize").toString());

            paramMap.put("billingCycle", billingCycle);
            paramMap.put("contractUserId", contractUserId);
            paramMap.put("pageNum", pageNum);
            paramMap.put("pageSize", pageSize);
        } catch (Exception e) {
            throw new ParamValidException("输入参数错误");
        }
        return paramMap;
    }
}